﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Data;

/// <summary>
/// CodeManager 的摘要描述
/// </summary>
public class CodeManager
{
	public CodeManager()
	{
		//
		// TODO: 在此加入建構函式的程式碼
		//
	}

    public DataTable GetData(string tableName, string colName)
    {
        return (from dr in GetAll(tableName, colName).AsEnumerable() where dr["Status"].ToString() == "Y" select dr).AsDataView().ToTable();
    }

    Dictionary<string, DataTable> _GetAll = new Dictionary<string, DataTable>();

    public DataTable GetAll(string tableName, string colName)
    {
        if (!_GetAll.ContainsKey(tableName + colName))
        {
            var db = new DB();
            
            var dt = db.Execute("SELECT * FROM CodeMap WHERE TableName = @TableName AND ColName = @ColName "
                        , new DBParameter("TableName", tableName), new DBParameter("ColName", colName));

            LocManager.Current.Translate(dt, "CodeMap", "Text");

            _GetAll.Add(tableName + colName, dt);
        }

        return _GetAll[tableName + colName];
    }

    public string GetText(string tableName, string colName, object value)
    {
        var dt = GetAll(tableName, colName);

        var result = (from row in dt.AsEnumerable() where row["value"].ToString() == value.ToString() select row).AsDataView();

        if (result.Count > 0)
        {
            return result[0]["text"].ToString();
        }
        else
        {
            return string.Empty;
        }
    }

    public static CodeManager Current
    {
        get
        {
            if (HttpContext.Current.Items["CodeManager"] == null)
            {
                HttpContext.Current.Items["CodeManager"] = new CodeManager();
            }

            return HttpContext.Current.Items["CodeManager"] as CodeManager;
        }
    }
}